package xyz.cerberu.cet.subtitle.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import xyz.cerberu.cet.global.domain.Global;
import xyz.cerberu.cet.resource.dao.ResourceDao;
import xyz.cerberu.cet.resource.domian.Resource;
import xyz.cerberu.cet.subtitle.dao.SubtitleDao;
import xyz.cerberu.cet.subtitle.domain.Subtitle;
import xyz.cerberu.cet.subtitle.exception.SubtitleNotExistException;

import java.sql.Date;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.List;

/**
 * @author β世界
 * Created on 18:25
 * @Description 字幕组service
 */
@Service
public class SubtitleServiceImpl {
    private final Global global;
    private final SubtitleDao subtitleDao;
    private final ResourceDao resourceDao;

    @Autowired
    public SubtitleServiceImpl(Global global, SubtitleDao subtitleDao, ResourceDao resourceDao) {
        this.global = global;
        this.subtitleDao = subtitleDao;
        this.resourceDao = resourceDao;
    }

    /** 时间间隔 **/
    private final static Long INTERVAL = 259200000L;

    /**
     * @author β世界 on 18:28 2020/4/27
     * @Description 获取字幕组的资源
     * 用于缓存字幕组的更新信息
     **/
    @Cacheable(value = "subtitle",key = "T(String).valueOf(#root.methodName).concat('-').concat(#subId)",unless = "#result.size() == 0")
    public List<Resource> resourceGroups(Integer subId) {
        return resourceDao.selectBySubID(subId);
    }

    /**
     * @author β世界 on 19:36 2020/6/25
     * 根据字幕组来查询最近的更新
     * @param subId: 字幕组的字段
     **/
    @Cacheable(value = "subtitle",key = "T(String).valueOf(#root.methodName).concat('-').concat(#subId)",unless = "#result.size() == 0")
    public List<Resource> getRecentUpdate(Integer subId) throws SubtitleNotExistException {
        // 查询字幕组
        Subtitle subtitle = subtitleDao.selectBySub_id(subId);
        // 没有查询到相关的字幕组就直接返回空w
        if(subtitle == null){
            // 抛出SubtitleNullException，来表示这个字幕组不存在
            throw new SubtitleNotExistException("字幕组不存在");
        }

        // 从数据库中查找
        long endTime = LocalDateTime.now().atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli();
        // 从数据库中查询
        return resourceDao.selectRangeTimeBySubtitle(
                subtitle.getSub_id(),
                new Date(endTime),
                new Date(endTime - INTERVAL)
        );
    }

    /**
     * @author β世界 on 15:28 2020/4/28
     * @Description 获取一个字幕组的资源总数
     **/
    public int resourceSum(Integer sub) {
        return subtitleDao.selectResourceSum(sub);
    }

    @Cacheable(value = "subtitle",key = "#root.methodName")
    public List<Subtitle> getAllSubtitle() {
        return subtitleDao.selectAllSubtile();
    }

    public Subtitle getSubtitle(Integer subId){
        return subtitleDao.selectBySub_id(subId);
    }
}
